import Component from "../Component.js";
import { CONF } from "../../configure/Assets.js"
import { _delay } from "../../experience/utils/F7.js";

export default class SimpleEditor extends Component {
    constructor() {
        super();

        this.pageNo = 1;
        this.pageNum = 0;
        this.pageSize = 10;
        this.uuid = null;
    }

    page() {
        this.$$("#simple-editor-prev").on("click", async () => {
            this.delay('prev', async () => {
                if (this.pageNo > 1 ) {
                    this.pageNo = this.pageNo - 1;
                }
                await this.pageno();
            }, 300);
        })

        this.$$("#simple-editor-next").on("click", async () => {
            this.delay('prev', async () => {
                if (this.pageNo < this.pageNum) {
                    this.pageNo = this.pageNo + 1;
                }
                await this.pageno();
            }, 300);
        })
    }

    async pageno() {
        const filter = { no: this.pageNo, size: this.pageSize };
        const data = await this.api.getMetasV2(filter);
        const metas = data.data;
        this.pageNo = 1; this.pageNum = Math.ceil(metas.total / this.pageSize);
        this.$$("#simple-editor-page").html(`总计: ${this.pageNum}页, 当前: ${this.pageNo}页`);
        this.$$("#simple-editor-table").empty();
        for (let i = 0; i < metas.data.length; i++) {
            const item = metas.data[i], id = `simple-editor-table-${i}`;
            const lookId = `simple-editor-table-look${i}`;
            const updateId = `simple-editor-table-update${i}`;
            const deleteId =`simple-editor-table-delete${i}`;
            let tr= `
                <tr id="${id}">
                    <td class="label-cell" style="width: 50px;">${i + 1}</td>
                    <td class="label-cell">${item.mine_code}</td>
                    <td class="label-cell" style="width: 220px;">
                        <span style="color: var(--primary-color); cursor: pointer; margin-right: 8px;" id="${lookId}">查看</span>
                        <span style="color: var(--primary-color); cursor: pointer; margin-right: 8px;" id="${updateId}">更新</span>
                        <span style="color: red; cursor: pointer;" id="${deleteId}">删除</span>
                    </td>
                </tr>
            `;
            this.$$("#simple-editor-table").append(this.$$(tr));

            this.$$(`#${lookId}`).on("click", async () => {
                this.editor.close();
                try {
                    this.app.dialog.preloader("正在获取矿图...");
                    const res = await this.api.getVector(item.meta_id);
                    if (res.code !== 0) {
                        this.toast(res.message);
                        this.app.dialog.close();
                        return;
                    }
                    const data = res.data;
                    this.drawer.init(data.meta, data.layers);
                    this.db.init(data).then(() => {
                        this.drawer.location().then(() => {
                            this.app.dialog.close();
                        });
                    });
                } catch(err) {
                    this.toast(err);
                    this.app.dialog.close();
                }
            });

            // 更新图纸meta
            this.$$(`#${updateId}`).on("click", async () => {
                this.editor.close();
                this.uuid = item.meta_id;
                this.$$("input[type='file']").val("");
                this.$$('#simple-editor-upload-name').val(item.mine_code);
                this.$$('#simple-editor-upload-name').attr('readonly', 'readonly');
                this.uploader = this.app.popup.create({ el: '.simple-editor-upload-popup' });
                this.uploader.open();
            });

            // 删除图纸
            this.$$(`#${deleteId}`).on("click", async () => {
                this.editor.close();
                try {
                    this.app.dialog.preloader("正在删除数据...")
                    const res = await this.api.delMeta(item.meta_id);
                    if (res.code !== 0) {
                        this.toast(res.message);
                    }
                    this.app.dialog.close();
                    await this.pageno();

                    this.db.clear(item.meta_id).then(() => {
                        this.drawer.refresh();
                    });
                } catch (err) {
                    this.toast(err);
                    this.app.dialog.close();
                    await this.pageno();
                }
            });
        }
    }

    // 上传Dxf文件
    async uploadDxf() {
        const file = new FormData();
        const code = this.$$('#simple-editor-upload-name').val();
        if (code === "") {
            this.toast("底图名称不能为空。");
            return;
        }

        const field = document.querySelector("input[type='file']");
        file.append("file", field.files[0]);
        file.append('name', CONF.MINE_NAME);
        file.append('code', code);
        if (this.uuid !== null) {
            file.append('uuid', this.uuid);
        }

        const name = field.files[0].name;
        const len = name.length;
        const dotDxf = name.substring(len-3, len);
        if (dotDxf === 'dxf') {
            this.app.dialog.preloader("正在上传图纸...");
            const result = await this.api.uploadDxf(file);
            if (result.code === 0) {
                this.app.dialog.close();
                this.app.dialog.preloader("正在获取矿图...");
                const data = await this.api.getVector(result.data.meta_id);
                if (data.code === 0) {
                    this.drawer.init(data.data.meta, data.data.layers);
                    this.db.init(data.data).then(() => {
                        this.drawer.location().then(() => this.app.dialog.close());
                    });
                }
            }
        } else {
            this.app.toast.create({
                text: '请选择AutoCAD的.dxf格式的文件,其他格式文件无效。',
                position: 'top',
                closeButton: false,
                closeTimeout: 3000
            }).open();
        }
    }

    template() {
        const div = `
            <div class="popup simple-editor-popup" style="height: 480px;">
                <header>底图管理</header>
                <article>
                    <div class="list inline-labels no-hairlines-md">
                        <div class="card data-table" style="height: 380px;">
                            <table>
                                <thead>
                                    <tr>
                                        <th class="label-cell">#</th>
                                        <th class="label-cell">名称</th>
                                        <th class="label-cell">操作</th>
                                    </tr>
                                </thead>
                                <tbody id="simple-editor-table"></tbody>
                            </table>
                        </div>
                    </div>
                </article>
                <footer style="display: flex; justify-content: space-between;">
                    <div>
                        <span id="simple-editor-prev" class="popup-page">
                            <<&nbsp;前一页&nbsp;&nbsp;&nbsp;&nbsp;
                        </span>
                        <span id="simple-editor-page"></span>
                        <span id="simple-editor-next" class="popup-page">
                            &nbsp;&nbsp;&nbsp;&nbsp;后一页&nbsp;>>
                        </span>
                    </div>
                    <div style="width: 200px; display: flex; justify-content: space-between;">
                        <button class="button button-fill color-orange popup-close" id="simple-editor-add">增加底图</button>
                        <button class="button button-fill color-gray popup-close">取消</button>
                    </div>
                </footer>
            </div>
        `;
        this.$$('#app').append(div);

        const div2 = `
            <div class="popup simple-editor-upload-popup" style="height: 200px;">
                <header>增加底图</header>
                <article>
                    <div class="list inline-labels no-hairlines-md">
                        <ul>
                            <li class="item-content item-input">
                                <div class="item-title item-label">底图名称</div>
                                <div class="item-inner">
                                    <div class="item-input-wrap">
                                        <label for="upload-mine-code">
                                            <input type="text" value="" id="simple-editor-upload-name" required validate>
                                        </label>
                                    </div>
                                </div>
                            </li>
                            <li class="item-content item-input" style="margin-top: 10px;">
                                <div class="item-inner">
                                    <input type="file" name="simple-editor-upload" accept=".dxf" />
                                </div>
                            </li>
                        </ul>
                    </div>
                </article>
                <footer>
                    <button class="button button-fill color-orange popup-close" id="simple-editor-upload">确定</button>
                    <button class="button button-fill color-gray popup-close">取消</button>
                </footer>
            </div>
        `
        this.$$('#app').append(div2);
    }

    control() {
        this.$$("#simple-editor").on("click", async () => {
            this.editor = this.app.popup.create({ el: '.simple-editor-popup' });
            this.editor.open();
            this.page();
            await this.pageno();
        });

        this.$$("#simple-editor-add").on("click", async () => {
            this.uuid = null;
            this.$$("input[type='file']").val("");
            this.$$('#simple-editor-upload-name').removeAttr("readonly");
            this.uploader = this.app.popup.create({ el: '.simple-editor-upload-popup' });
            this.uploader.open();
        });

        this.$$("#simple-editor-upload").on("click", async () => {
            _delay('simple-editor-upload', async () => {
                await this.uploadDxf();
            }, 500);
        });
    }
}